<template>
  <div class="container">
    <div class="app-container">
      <div class="add-btn">
        <el-button type="primary" size="mini" @click="visible = true">添加角色</el-button>
      </div>

      <el-table v-loading="loading" :data="list">
        <el-table-column label="序号" width="80">
          <template #default="{ $index }"> {{ $index + 1 + 5 * (page - 1) }} </template>
        </el-table-column>

        <el-table-column label="角色" prop="name">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.name" />
            <span v-else>{{ row.name }}</span>
          </template>
        </el-table-column>

        <el-table-column label="启用" prop="state" width="120">
          <template #default="{ row }">
            <el-switch v-if="row.isEdit" v-model="row.editRow.state" :active-value="1" :inactive-value="0" />
            <span v-else> {{ row.state === 1 ? "已启用" : "未启用" }}</span>
          </template>
        </el-table-column>

        <el-table-column label="描述" prop="description">
          <template #default="{ row }">
            <el-input v-if="row.isEdit" v-model="row.editRow.description" type="textarea" />
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column label="操作">
          <template #default="{ row }">
            <div v-if="row.isEdit">
              <el-button type="text" @click="onUpdate(row)">确认</el-button>
              <el-button type="text" @click="onCancel(row)">取消</el-button>
            </div>

            <div v-else>
              <el-button type="text" @click="showPerm(row.id)">分配权限</el-button>
              <el-button type="text" @click="row.isEdit = true">编辑</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="onDel(row.id)"
              >
                <el-button slot="reference" type="text">删除</el-button>
              </el-popconfirm>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <el-row type="flex" justify="end">
        <el-pagination
          :current-page="page"
          layout="prev, pager, next"
          :total="total"
          :page-size="5"
          @current-change="onCurrentChange"
        />
      </el-row>
    </div>

    <el-dialog
      :visible.sync="visible"
      title="新增角色"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="mini"
        label-width="160px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="formData.name" />
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch
            v-model="formData.state"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input v-model="formData.description" type="textarea" />
        </el-form-item>
        <el-form-item>
          <el-row type="flex" justify="center">
            <el-button type="primary" @click="onSubmit">确定</el-button>
            <el-button @click="visible = false">取消</el-button>
          </el-row>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="permVisible">
      <el-tree
        ref="permRef"
        check-strictly
        :default-checked-keys="permIds"
        node-key="id"
        show-checkbox
        :data="permList"
        :props="{label:'name'}"
        default-expand-all
        :expand-on-click-node="false"
      />
      <el-row type="flex" justify="center">
        <el-button type="primary" @click="onAssignPerm">确定</el-button>
        <el-button @click="permVisible=false">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>

import { getPermsAPI } from '@/api/permission'
import { addRoleAPI, assignPermAPI, delRoleAPI, getRolesAPI, getRolesDetailAPI, updateRoleAPI } from '@/api/role'
import { list2Tree } from '@/utils'
export default {
  name: 'Role',
  data() {
    return {
      permIds: '',
      permList: [],
      permVisible: false,
      list: [],
      total: 0,
      page: 1,
      loading: false,
      visible: false,
      formData: {
        name: '',
        state: 0,
        description: ''
      },
      rules: {
        name: [{ required: true, message: '名称不能为空', trigger: 'blur' }],
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  watch: {
    visible(newVal) {
      if (!newVal) {
        this.$refs.formRef.resetFields()
      }
    }
  },
  created() {
    this.onLoad()
  },
  methods: {
    async  onAssignPerm() {
      const xxx = this.$refs.permRef.getCheckedKeys()
      await assignPermAPI({ id: this.id, permIds: xxx })
      this.$message.success('分配成功')
      this.permVisible = false
      this.onLoad()
    },
    async  showPerm(id) {
      this.id = id
      const { data } = await getPermsAPI()
      this.permList = list2Tree(data, 0)
      const res = await getRolesDetailAPI(id)
      // console.log(res)
      this.permIds = res.data.permIds
      this.permVisible = true
    },
    async onDel(id) {
      await delRoleAPI(id)
      this.$message.success('删除成功')
      if (this.list.length === 1) {
        this.page--
      }
      this.onLoad()
    },
    async onUpdate(row) {
      if (row.editRow.name && row.editRow.description) {
        await updateRoleAPI({
          id: row.id,
          ...row.editRow })
        this.$message.success('更新成功')
        Object.assign(row, {
          ...row.editRow,
          isEdit: false // 退出编辑模式
        }) // 规避eslint的误判
      } else {
        this.$message.warning('角色和描述不能为空')
      }
    },
    onCancel(row) {
      row.isEdit = false
      row.editRow.name = row.name
      row.editRow.state = row.state
      row.editRow.description = row.description
    },
    async onSubmit() {
      await this.$refs.formRef.validate()
      await addRoleAPI(this.formData)
      this.$message.success('新增成功')
      this.onLoad()
      this.visible = false
    },
    async onLoad() {
      this.loading = true
      const { data } = await getRolesAPI({ page: this.page, pagesize: 5 })
      this.loading = false
      this.list = data.rows
      this.list.forEach((item) => {
        this.$set(item, 'isEdit', false)
        //  使用$set设置editRow数据
        this.$set(item, 'editRow', {
          name: item.name,
          state: item.state,
          description: item.description
        })
      })

      this.total = data.total
    },
    onCurrentChange(page) {
      this.page = page
      this.onLoad()
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 10px;
  font-size: 14px;
}
</style>
